import { AppRegistry, BackHandler, ToastAndroid } from 'react-native'
import { StackNavigator, TabNavigator, TabBarBottom } from 'react-navigation'

import React, { Component } from 'react'
import axios from 'axios'
import GetSetStorge from './src/common/GetSetStorge'
import { configRoute, RouteHelper } from 'react-navigation-easy-helper'
import Home from './src/view/Home/Home'
import Splash from './Splash'



let routes = [];
let lastBackPressed = null
class Index extends Component {

	async getToken() {
		return await GetSetStorge.getStorgeAsync(`token`)
	}

	async axiosFilter() {
		// token统一配置
		axios.interceptors.request.use(
			config =>
				this.config(config)
			, function (error) {
				return Promise.reject(error)
			}
		)
	}

	async config(config) {
		let token = await this.getToken()
		config.headers['token'] = token
		return config
	}

	async loginConfig(routeName, params) {
		let token = await this.getToken()
		if (!token && needLoginPage.indexOf(routeName) !== -1) {
			RouteHelper.push('Login', {
				successCallBack: () => {
					RouteHelper.push(routeName, params)
				}
			})
			// alert('跳登陆'+ routeName)
			return false
		}
		return true
	}

	async pageFilter() {
		//跳转拦截器用法
			RouteHelper.routeInterceptor = (routeName, params) => this.loginConfig(routeName, params)
	}

	componentDidMount() {
		this.axiosFilter()
		// this.pageFilter()

		BackHandler.addEventListener('hardwareBackPress', this.onBackAndroid)
	}

	componentWillUnmount() {
		BackHandler.removeEventListener('hardwareBackPress', this.onBackAndroid)
		lastBackPressed = null
	}

	onBackAndroid() {
		if (routes.length === 2) { // 根界面
			if (lastBackPressed && lastBackPressed + 2000 >= Date.now()) {
				BackHandler.exitApp()
				return false
			}
			lastBackPressed = Date.now()
			ToastAndroid.show('再按一次退出应用', ToastAndroid.SHORT)
			return true
		}
	}

	render() {
		return (
			<RootNavigator
				onNavigationStateChange={(prevNav, nav, action) => {
					console.log('prevNav=', prevNav)
					console.log('nav=', nav)
					console.log('action=', action)
					routes = nav.routes
				}}
			/>
		)
	}
}

export default Index


/*
 * 初始化StackNavigator
 */
const RootNavigator = StackNavigator(
	configRoute({
		//默认加载第一个页面，这里用来注册需要跳转的页面 相当于Manifest.xml文件
		Splash: {
			screen: Splash,
			navigationOptions: {
				header: null,
				gesturesEnabled: false // 是否允许右滑返回，在iOS上默认为true，在Android上默认为false
			}
		},
		App: {
			screen: Home,
			navigationOptions: {
				header: null,
				gesturesEnabled: false
			}
        },
	})
)


console.disableYellowBox = true // 去除警告
AppRegistry.registerComponent('sjhhLocation', () => Index);
